﻿using System;
using System.Linq;

using Spencen.Mobile.UI.Navigation;
using Spencen.Mobile.UI.Controls;
using Spencen.Mobile.UI;
using Spencen.Mobile.Markup;
using Spencen.Mobile.UI.Commanding;

using Commute.Model;
using Spencen.Mobile.UI.Templating;

namespace Commute.Presenters
{
    public class RoutePresenter
    {
        private IDrawingHost _host;
        private INavigator _navigator;
        private Timetable _timetable;

        public RoutePresenter( INavigator navigator )
        {
            BackCommand = new DelegateCommand( Back );
            ResultCommand = new DelegateCommand( Result );

            _navigator = navigator;
        }

        public ICommand BackCommand { get; private set; }
        public ICommand ResultCommand { get; private set; }

        public View CreateView( IDrawingHost host )
        {
            _host = host;

            // XAML Loading
            var text = (System.IO.Stream)System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream( "Commute.Views.RouteView.xml" );
            var xamlRenderer = new XamlRenderer( host, this );
            return (View) xamlRenderer.Render( text );
        }

        public ObservableList Routes { get; private set; }

        public void Initialize( Timetable timetable )
        {
            var routes = from s in timetable.Services
                         from r in s.Routes
                         group r by r.Name into routeNames
                         orderby routeNames.Key
                         select new
                         {
                             Name = routeNames.Key,
                             Description = routeNames.First().Description
                         };

            Routes = new ObservableList( routes );
            
            _timetable = timetable;
        }

        private void Back()
        {
            _navigator.Back();
        }

        private void Result()
        {
            var presenter = new ResultPresenter( _navigator );
            presenter.Initialize( _timetable, "From City" );
            _navigator.Forward( presenter.CreateView( _host ) );
        }
    }
}
